const DB = require('../../config/db')

// 查询所有用户
const list = async ctx => {
  const {page,pageSize} = ctx.request.query
  const data = await DB.find('user',{},{},{page,pageSize})
  let feedback
  try {
    feedback = {code:200,msg:'success',data}
  }catch (e){
    console.log(e);
    feedback = {code:500,msg:'server error'}
  }
  ctx.body = feedback
}

// 新增用户
const addUser = async ctx => {
  const {username,nickname,age,sex} = ctx.request.body
  await DB.insert('user',{username,nickname,age,sex})
  let feedback
  try {
    feedback = {code:200,msg:'add success'}
  }catch (e) {
    console.log(e);
    feedback = {code:500,msg:'server error'}
  }
  ctx.body = feedback
}

//编辑用户
const editUser = async ctx => {
  const {_id,username,nickname,age,sex} = ctx.request.body
  await DB.update('user',{'_id': DB.getObjectID(_id)},{username,nickname,age,sex})
  let feedback
  try {
    feedback = {code:200,msg:'edit success'}
  }catch (e) {
    console.log(e);
    feedback = {code:500,msg:'server error'}
  }
  ctx.body = feedback
}

//删除用户
const deleteUser = async ctx => {
  const {_id} = ctx.request.query._id
  await DB.delete('user',_id)
  let feedback
  try {
    feedback = {code:200,msg:'delete success'}
  }catch (e) {
    console.log(e);
    feedback = {code:500,msg:'server error'}
  }
  ctx.body = feedback
}

module.exports = { list, addUser, editUser, deleteUser }
